/*
 * Copyright (c) 2011. This file is public under GPLv3 license.
 * For more information about license please refer to http://www.gnu.org/licenses/gpl.html
 */

package com.freetools.watchdog.commands;

import com.freetools.watchdog.exceptions.ParametersErrorException;
import com.freetools.watchdog.model.CommandName;
import com.freetools.watchdog.model.IColumn;
import com.freetools.watchdog.model.IModelHolder;

import java.util.regex.Pattern;

/**
 * Set sort clause into query statement of model
 *
 * @author Michael Morozov
 */
@CommandName("sort")
public class SortCmd extends Command
{

    public void execute(IModelHolder model) throws ParametersErrorException
    {
        checkParameters(1, Integer.MAX_VALUE);
        StringBuilder sb = new StringBuilder(" order by ");

        for (String s : getParameters())
        {
            boolean added = false;
            for (IColumn column : model.getColumns())
            {
                if (s.equalsIgnoreCase(column.getName()))
                {
                    sb.append(column.getName()).append(",");
                    added = true;
                    break;
                }
            }
            if (!added)
                throw new ParametersErrorException(
                        "Sort parameter with name " + s +
                                " does not match to any specified columns");
        }
        sb.deleteCharAt(sb.length() - 1);

        model.setQuery(
                Pattern.compile("\\s+order by .*$", Pattern.DOTALL | Pattern.MULTILINE | Pattern.CASE_INSENSITIVE)
                        .matcher(model.getQuery()).replaceAll("") + sb
        );
    }

    @Override
    public boolean isMultipleParametrized()
    {
        return true;
    }
}
